<script setup>
import { ref, watch, onMounted } from "vue";
import SideMenu from '../components/side-menu/SideMenu.vue';
import IconSvg from '../components/IconSvg.vue';
import DropDown from '../components/DropDown.vue';
import { useRoute } from 'vue-router';
import { useRouter } from 'vue-router';
import axios from '../axios/axios';
import mqttService from '../utils/mqttService';
import Message from "../components/Message/Message.js";
import { getUserRole } from "../api/user.js";

const router = useRouter();
// 响应式变量
const headerTitle = ref("");
const route = useRoute();
const activePath = ref(route.path);
const userMenuItems = ref([
  {
    label: '退出登录',
    actionKey: 'logout', // 退出登录的标识
    isDanger: true, // 危险操作（红色样式）
    disabled: false
  }
]);

// 2. 处理菜单项点击事件（核心：根据actionKey执行不同逻辑）
const handleUserMenuClick = (actionKey) => {
  switch (actionKey) {
    case 'logout':
      localStorage.removeItem('token');
      router.push('/login');
      break;
    default:
      console.log('未知操作：', actionKey);
  }

};
// 连接选项
const connectOptions = {
  userName: 'your-username',
  password: 'your-password',
  cleanSession: true
};



// 发送消息
function sendMqttMessage() {
  mqttService.sendMessage('your/topic', 'Hello MQTT');
}

// 断开连接
function disconnectMqtt() {
  mqttService.disconnect();
}
onMounted(async () => {
  const token = localStorage.getItem('token');
  var role = 0
  if (token) {
    role = await getUserRole();
    if (role !== null) {
      switch (role) {
        case 0:
          headerTitle.value = "管理员";
          break;
        case 1:
          headerTitle.value = "生产管理员";
          break;
        case 2:
          headerTitle.value = "物料工";
          break;
        case 3:
          headerTitle.value = "操作员";
          break;
      }
    }
  }
  axios.get("/api/service/select").then(res => {
    if (res.data.Code == "200") {
      var data = res.data.Data
      if (data.mqttserveraddress != null && data.mqttserveraddress != "") {
        const mqttUrl = data.mqttserveraddress
        mqttService.createClient(mqttUrl);
        const connectOptions = {
          cleanSession: true
        };
        // 连接服务器
        mqttService.connect(connectOptions)
          .then(() => {
            // 订阅主题
            mqttService.subscribe('SyncUser-CYGL/' + data.userid);
            console.log('SyncUser-CYGL/' + data.userid);
            // 设置消息接收回调
            mqttService.onMessage((message) => {
              console.log('收到消息:', message.payloadString);
              // 处理消息
              const topic = message.destinationName;
              if (topic == 'SyncUser-CYGL/' + data.userid) {
                var info = JSON.parse(message.payloadString)
                if (info.role !== role) {
                  axios.get("/api/user/syncuser?cardNumber=" + info.cardNumber).then(res1 => {
                    if (res1.data.Code == "200") {
                      Message.warn('您的角色已发生变更，重新登录')
                      localStorage.removeItem('token');
                      localStorage.removeItem('role');
                      localStorage.setItem('token', res1.data.Data);
                      localStorage.setItem('role', info.role);
                      router.push('/');
                      setTimeout(() => {
                        window.location.reload();
                      }, 100);
                    }
                  })

                }
              }
            });
          })
          .catch((error) => {
            Message.warn('MQTT服务连接失败：' + error.errorMessage)
            console.error('连接失败:', error);
          });
      }
    }
  })
});



// 监听路由变化，同步activePath
watch(
  () => route.path,
  (newPath) => {
    activePath.value = newPath;
  },
  { immediate: true }
);

</script>

<template>
  <div class="flex h-full w-full box-border">
    <!-- 侧边栏 -->
    <div class="min-w-[220px] h-full flex flex-col px-4 border-r border-gray-100 bg-white">
      <div class="flex justify-center mt-5 mb-4 w-[100%]">
        <span class="font-bold text-2xl">冲压加工管理</span>
      </div>
      <div class="main-view-sidemenu main-view-child">
        <SideMenu :active-path="activePath" />
      </div>
    </div>

    <!-- 主内容区 -->
    <div class="flex-1 h-full flex flex-col">
      <!-- 顶部导航 -->
      <div class="h-[60px] flex px-[20px] border-b border-gray-100 items-center bg-white">
        <div class="flex-1 text-left font-semibold text-lg text-[#222222]">
          {{ headerTitle }}
        </div>
        <div class="flex items-center gap-[20px] pr-[10px]">
          <DropDown :menu-items="userMenuItems" icon-size="medium" @menu-click="handleUserMenuClick">
            <template #trigger>
              <IconSvg name="user-head" class="h-[30px] w-[30px] text-[#323232]" />
            </template>
          </DropDown>

        </div>
      </div>
      <div class="flex-1 w-full px-[20px] py-[20px] overflow-y-auto bg-[#F5F5F5]">
        <!-- <div class="bg-[#F5F5F5] h-full w-full px-[20px] pt-[20px] ">

        </div> -->
        <RouterView />
      </div>

    </div>
  </div>
</template>

<style scoped>
/* 确保全局盒模型一致 */
:root {
  box-sizing: border-box;
}

*,
*::before,
*::after {
  box-sizing: inherit;
}
</style>